﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Data;
using System.Reflection;

namespace Crm.Web
{
    public class Parametre
    {
        List<SqlParameter> prmlist = new List<SqlParameter>();

        public void Ekle(string adi, SqlDbType type, object value, int size)
        {
            if (adi.IndexOf('@') > -1)
            {
                prmlist.Add(new SqlParameter(adi, type, size) { Value = value });
            }
            else
            {
                prmlist.Add(new SqlParameter("@" + adi, type, size) { Value = value });
            }
        }

        public void Ekle(string adi, SqlDbType type, object value)
        {
            if (adi.IndexOf('@') > -1)
            {
                prmlist.Add(new SqlParameter(adi, type) { Value = value });
            }
            else
            {
                prmlist.Add(new SqlParameter("@" + adi, type) { Value = value });
            }
        }

        public SqlParameter[] ToArray()
        {
            return prmlist.ToArray();
        }

        public SqlParameter[] ToArray(object obje)
        {
            List<SqlParameter> list = new List<SqlParameter>();
            Type t = obje.GetType();
            foreach (PropertyInfo item in t.GetProperties())
            {
                object val = item.GetValue(obje, null);
                if (val != null)
                {
                    SqlParameter prm = new SqlParameter("@" + item.Name, GetSqlDbType(item.PropertyType.Name));
                    prm.Value = val;
                    list.Add(prm);
                }
            }
            return list.ToArray();
        }

        private SqlDbType GetSqlDbType(string columnType)
        {
            switch (columnType)
            {
                case "Int32":
                    return SqlDbType.Int;
                case "Double":
                case "Decimal":
                    return SqlDbType.Float;
                case "DateTime":
                    return SqlDbType.DateTime;
                case "Boolean":
                    return SqlDbType.Bit;
                case "Byte":
                    return SqlDbType.TinyInt;
                default:
                    return SqlDbType.VarChar;
            }
        }

    }
}